# coding:utf8
"""
    采用分割的文件；
    m-1.0 -2019/10/14

"""
from os.path import exists, getsize
from os import remove
# Local
from m_sendEmail import send_email
from m_constant import f_logRepeat, f_ipv4, f_logSent, f_infoEmail126, f_infoEmailQq, nowTime, ipv4, _str126, _strQq


def init_email_info(file_name, info):
    """ 初始化-邮件信息 """
    with open(file_name, 'w', encoding='utf8') as fEmail:
        fEmail.write(info)


def writeLog(file, mail, msg_):
    with open(file, 'a', encoding='gbk') as fLog:
        fLog.write(f'[{nowTime}] | ' + f'{mail}'.ljust(18) + '|' + f'{ipv4}'.center(16) + f'| {msg_}\n')


def send_IP():
    _title = f'[{nowTime}]Your New IP' + f'{ipv4}'.center(16)
    _msg = f'[{nowTime}] New ipv4 is {ipv4.center(16)}'
    _r1, _mail = send_email(f_infoEmailQq, _title, _msg)
    if _r1 == -1: _r1, _mail = send_email(f_infoEmail126, f'[{nowTime}]你的新地址', f'[{nowTime}] New ipv4  {ipv4}')
    if _r1 == 0:  open(f_ipv4, 'w', encoding='utf8').write(ipv4)
    if _r1 == 0:  writeLog(f_logSent, _mail, f'IP 更新 ')
    if _r1 == -1:  writeLog(f_logSent, _mail, f'发送失败, 查看ErrorTraceback.txt了解详情。')


def main():
    if not exists(f_infoEmail126): init_email_info(f_infoEmail126, _str126)
    if not exists(f_infoEmailQq): init_email_info(f_infoEmailQq, _strQq)
    if exists(f_logRepeat) and getsize(f_logRepeat) > 100000: remove(f_logRepeat)
    if not exists(f_ipv4) or not ipv4 == open(f_ipv4, 'r', encoding='utf8').read(): send_IP()
    else:
        writeLog(f_logRepeat, 'NoMail', 'None')
        print('Keep previous IPv4 address.')
    # elif not ipv4 == open(f_ipv4, 'r', encoding='utf8').read(): send_IP()
    # if exists('./_sup/ipv4.ini'): remove('./_sup/ipv4.ini')


if __name__ == '__main__':
    main()
